<template>
	<div>
		<van-nav-bar title="文章管理" placeholder fixed />
		<li v-for="(item, index) in arrReverse" :key="index">
			<van-cell title="文章名" :value="item.title" size="large" />
			<van-cell title="文章内容" size="large" :label="item.content" />
			<van-field name="switch">
				<template #input> 是否公开:<van-switch v-model="item.status" @change="amend(item.id)" /> </template>
			</van-field>
			<van-button plain type="primary" @click="delfn(item.id)">删除</van-button>
			<van-button plain type="primary" @click="isAmend(item)">编辑</van-button>
			<p></p>
			<div v-show="bianji && currentEditIndex === item.id">
				<van-cell-group inset>
					<van-field v-model="edit.title" label="文章名" />
					<van-field v-model="edit.content" label="文章名" />
					<van-field name="switch">
						<template #input> 是否公开:<van-switch v-model="edit.status" /> </template>
					</van-field>
				</van-cell-group>
				<van-button plain type="primary" @click="send(edit)">保存</van-button>
			</div>
		</li>
	</div>
</template>

<script setup>
	import http from '@/utils/request';
	import { ref } from 'vue';
	const listArr = ref([]);
	const arrReverse = ref([]);
	const edit = ref({});
	const currentEditIndex = ref(null);
	function loadList() {
		http({
			url: '/posts',
			method: 'get',
		}).then((r) => {
			console.log(r.data);
			listArr.value = r.data;
			arrReverse.value = listArr.value.reverse();
		});
	}
	loadList();
	function amend(id) {
		http({
			url: '/posts/' + id,
			method: 'patch',
			data: {
				status: listArr.value.find((item) => item.id === id).status,
			},
		}).then((r) => {
			console.log(r.data);
		});
	}
	const bianji = ref(false);
	function delfn(id) {
		http({
			url: '/posts/' + id,
			method: 'delete',
		}).then((r) => {
			console.log(r);
			loadList();
		});
	}
	// 编辑
	function isAmend(item) {
		bianji.value = true;
		currentEditIndex.value = item.id;
		edit.value = { ...item };
	}
	function send(edit) {
		console.log(edit.id);
		http({
			url: '/posts/' + edit.id,
			method: 'patch',
			data: {
				title: edit.title,
				content: edit.content,
				status: edit.status,
			},
		}).then((r) => {
			console.log(r.data);
			bianji.value = false;
			loadList();
		});
	}
</script>

<style scoped lang="scss"></style>
